<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 用户接口
 * 
 * @author 陈蕾
 */
class Controller_Member extends Controller_Base
{
	/**
	 * 注册
	 */
	public function action_register()
	{
		$this->test(array(
			'name' => 'test2',
			'password' => '12345',
			'sex' => '',
			'email' => 'test@a.com',
			'avatar' => 1,
			'mate_avatar' => 1
		));
		
		$member = ORM::factory('member');
		$member->need_check_password();
		$member->values($this->_params);
		
		$validate = $member->validate();
		$validate->callback('name', array('Model_Member', 'username_available'));
		
		if ($member->check()) {
			$member->save();
			$this->output(1);
		} else {
			$errors = $validate->errors('member');
			$this->error(array_shift($errors));
		}
	}
	
	/**
	 * 登录接口
	 */
	public function action_login()
	{
		// 测试数据
		$this->test(array(
			'username' => 'cl',
			'password' => 'chenlei'
		));
		
		$username = $this->get('username');
		$password = $this->get('password');
		
		if (!$username || !$password) {
			$this->error('用户名或者密码不能为空！');
			return;
		}
		
		$result = Model::factory('member')->login($username, $password);
		if (!$result) {
			$this->error('登录失败，请确认用户名和密码是否正确！');
			return;
		}
		
		if ($result['locked']) {
			$this->error('登录失败，此用户已被锁定！');
			return;
		}
		
		// 基础数据
		$result = $this->reduceResult($result, array(
			'id', 'name', 'sex', 'email', 'avatar', 'mate_avatar', 'last_login'
		));
		
		// 总课时统计
		$lesson_stats = Model_Lesson::getStats();
		// 已学课时统计
		$finished_stats = Model_LessonProgress::getStats($result['id']);
		
		// 查找学到哪个章节
		$found = false;
		foreach ($lesson_stats as $chapter_id => $count) {
			$finished = array_key_exists($chapter_id, $finished_stats) ? 
				$finished_stats[$chapter_id] : 0;
			// 未考虑章节无课时的情况
			if ($finished < $count) {
				$found = true;
				break;
			}
		}
		
		// 找到未学习的章节
		if ($found) {
			$current = Model_LessonProgress::getCurrent($result['id'], $chapter_id);
			if (!$current) {
				$lesson = Model_Lesson::getFirst($chapter_id);
			} else {
				$model = ORM::factory('lesson', $current['lesson_id']);
				if ($current['exam_score'] < 60) {
					$lesson = $model->as_array();
				} else {
					$lesson = $model->getNext();
				}
			}
			
			if ($lesson) {
				$lesson['id'] = $lesson['client_id'];
				$lesson = $this->reduceResult($lesson, array('id', 'name'));
			}
			
			$chapter = ORM::factory('chapter', $chapter_id)->as_array();
			if ($chapter) {
				$chapter = $this->reduceResult($chapter, array('id', 'name'));
			}
			
			$result['current'] = array(
				'chapter' => $chapter,
				'lesson' => $lesson,
			);
		} else {
			// 
			$result['current'] = NULL;
		}
		
		$this->output($result);
	}
	
	/**
	 * 更新资料
	 */
	public function action_update()
	{
		if (!$this->id) {
			$this->error('未知用户！');
			return false;
		}
		
		$this->test(array(
			'sex' => '',
			'email' => 'test@b.com',
			'avatar' => 1,
			'mate_avatar' => 1
		));
		
		$member = ORM::factory('member', $this->id);
		
		$validate = Validate::factory($this->_params);
		$validate->filters('sex', array('intval' => NULL));
		$validate->filters('avatar', array('intval' => NULL));
		$validate->filters('mate_avatar', array('intval' => NULL));
		$validate->rules('email', array(
			'not_empty' => NULL,
			'email'     => NULL,
        	'max_length' => array('16')
        ));
		$validate->rules('avatar', array(
			'Model_Member::verify_avatar' => NULL
        ));
		$validate->rules('mate_avatar', array(
			'Model_Member::verify_avatar' => NULL
        ));
		
		if ($validate->check()) {
			$member->values($validate->as_array());
			$member->save();
			$this->output(1);
		} else {
			$errors = $validate->errors('member');
			$this->error(array_shift($errors));
		}
	}
	
	//==========================================================================
	// Utils
	//==========================================================================
	
	/**
	 * 获取下一个课时
	 * 
	 * @param Model_Lesson $lesson 课时模型对象
	 * @return array chapter_id, lesson_id
	 */
	private function getNext($lesson)
	{
		$next = $lesson->getNext();
		
		if ($next) {
			return array(
				'chapter_id' => $lesson->chapter_id,
				'lesson_id'  => $next['client_id']
			);
		}
		
		$chapter = ORM::factory('chapter')->find($lesson->chapter_id);
		if (!$chapter->loaded()) {
			return null;
		}
		
		$next_chapter = $chapter->getNext();
		if (!$next_chapter) {
			return null;
		}
		
		$first = Model_Lesson::getFirst($next_chapter['id']);
		return array(
			'chapter_id' => $next_chapter['id'],
			'lesson_id'  => $first ? $first['client_id'] : 0
		);
	}
}